const {Menu,dialog} = require('electron')
const path = require('path')
const got = require('got')
const imageType = require('image-type')
const randomstring = require('randomstring')
const fs = require('fs')


const saveas =  (srcUrl) =>{
    if(srcUrl){
        const contextMenu = Menu.buildFromTemplate([
            {
                label:'图片另存为',
                click:()=>{
                     got.get(srcUrl).then(async (response)=>{
                        // 二进制流
                        const chunk = Buffer.from(response.rawBody)
                        // 获取文件的扩展名称
                        const imageExt = imageType(chunk)

                        const {filePath,canceled} = await dialog.showSaveDialog({
                            title:'图片另存为',
                            defaultPath:path.resolve(__dirname,'../public/upload/'+randomstring.generate(10)+'.'+imageExt.ext)
                        })
                        
                        if(canceled){
                            return;
                        }

                        // 写入文件
                        fs.writeFileSync(filePath,chunk)

                     }).catch(()=>{})
                },
                // 快捷键
                accelerator:'CommandOrControl+S'
            }
        ])
        contextMenu.popup()
    }
}

module.exports = saveas